<template>
  <div>
    <a class="bubble bubble-yellow" @click="bubbleClick" href="javascript:;">
      <span class="bubble-tail"></span>
      <span :class="waveClass"></span>
      <span class="bubble-tip" v-if="state == 0 && !canPlay">1元偷听</span>
      <span class="bubble-tip" v-if="state == 0 && canPlay">点击播放</span>
      <span class="bubble-tip" v-if="state == 1">正在播放</span>
      <span class="bubble-tip" v-if="state == 2">已经暂停</span>
    </a>
    <!--
    <span v-if="seconds" class="bubble-duration">{{ seconds }}"</span>
    -->
    <audio :id="id" :src="audioUrl"></audio>
  </div>

</template>

<script>

import qs from 'qs'
import util from '@/util/util'
import { mapGetters } from 'vuex'

export default {
  name: 'Bubble',
  data () {
    return {
      state: 0,
      id: 'audio-bubble-' + this.index,
      canPlay: this.isBought,
      displayTime: this.seconds,
      timer: null,
      waveClass: 'wave3',
    }
  },
  props: {
    seconds: {
      type: Number,
      default: 0
    },
    type: {
      type: [Number, String],
      default: 1
    },
    reward: {
      type: [Number, String],
      default: 1
    },
    audioUrl: String,
    localId: String,
    index: Number,
    objectId: Number,
    isBought: {
      type: [Boolean],
      default: false
    }
  },
  beforeDestroy () {
    if (this.timer) {
      window.clearInterval(this.timer)
      this.timer = null
    }
  },
  beforeCreate () {
    var webUrl = window.location.href
    var jsApiList = [
      "chooseWXPay",
      "playVoice",
      "pauseVoice",
      "stopVoice",
      "onVoicePlayEnd"
    ]
    if (util.isAndroid()) {
      var that = this
      setTimeout(function() {
        that.SDKRegister(that, webUrl, jsApiList)
      }, 500)
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  methods: {
    wxPay: function() {
      var that = this
      var params = {
        type: this.type, // 0：提问，1：偷听，2：充值
        amount: this.reward,
      }
      if (typeof(this.objectId) !== 'undefined') {
        params.object_id = this.objectId
      }
      this.axios.post('/finances/pay/', qs.stringify(params))
      .then(function (res) {
        if (!res.data.pay_type) {
          var payload = {
            amount: parseFloat(that.reward)
          }
          that.$store.dispatch('payBalance', payload)
          that.canPlay = true
          that.$emit('payed', that.index)
          that.$toast.success('使用余额支付成功')
          return
        }
        var payInfo = res.data.pay_info
        var timeStamp = payInfo.timeStamp.toString()
        that.wx.chooseWXPay({
          timestamp: timeStamp, 
          nonceStr: payInfo.nonceStr,
          package: payInfo.package,
          signType: payInfo.signType,
          paySign: payInfo.paySign,
          success: function (res) {
            // 支付成功后的回调函数
            that.canPlay = true
            that.$emit('payed', that.index)
          },
          fail: function (res) {
            console.log(res.errMsg)
          }
        });
      })
      .catch(function (error) {
        if (error.response) {
          that.$toast.fail(error.response.data.detail)
        } else {
          that.$toast.fail('请求出错')
        }
      })
    },
    bubbleClick: function () {
      if (!util.isWechat()) {
        return this.$toast.fail('请在微信中打开')
      }
      var that = this
      if (!this.canPlay) {
        if (this.reward > this.userInfo.balance) {
          return this.wxPay()
        } else {
          return this.$dialog.confirm({
            title: '支付提醒',
            message: '使用余额支付偷听的费用？'
          }).then(() => {
            return that.wxPay()
          }).catch(() => {
            return
          })
        }
      }
      if (this.state == 0) {
        this.play()
      } else if (this.state == 1) {
        this.pause()
      } else if (this.state == 2) {
        this.play()
      }
    },
    onAudioPlayEnd: function() {
      this.$toast.clear()
      this.state = 0
      this.waveClass = 'wave3'
      if (this.timer) {
        window.clearInterval(this.timer)
        this.timer = null
      }
    },
    onCanPlay: function() {
      this.$toast.clear()
      var that = this
      this.timer = setInterval(function() {
        that.displayTime --
        var count = that.seconds - that.displayTime
        var waveStatus = count % 3
        if (!waveStatus) {
          that.waveClass = 'wave3'
        } else {
          that.waveClass = 'wave' + waveStatus
        }
      }, 1000)
    },
    play: function () {
      this.state = 1
      var that = this
      if (this.localId === undefined) {
        var audioItem = document.getElementById("audio-bubble-"+ this.index);
        this.$toast.loading({ duration: 0 })
        audioItem.play();
        // 监听开始播放
        audioItem.oncanplay = this.onCanPlay()
        // 监听播放完成
        audioItem.addEventListener('ended', this.onAudioPlayEnd)
        audioItem.addEventListener('error', this.onAudioPlayEnd)
      } else {
        this.wx.playVoice({
          localId: this.localId
        })
        this.onCanPlay()
        this.wx.onVoicePlayEnd({
          success: function(res) {
            that.onAudioPlayEnd()
          }
        })
      } 
    },
    pause: function () {
      this.state = 2
      this.waveClass = 'wave3'
      if (this.timer) {
        window.clearInterval(this.timer)
        this.timer = null
      }
      if (this.localId === undefined) {
        var audioItem = document.getElementById("audio-bubble-"+ this.index);
        audioItem.pause();
      } else {
        this.wx.pauseVoice({
          localId: this.localId
        })
      }
    }
  }
}

</script>

<style lang="scss">

.bubble {
  display: block;
  background: #1ccda6;
  line-height: 1.8rem;
  height: 1.8rem;
  border-radius: .9rem;
  text-align: center;
  width: 8.25rem;
  color: #fff;
  font-size: .6rem;
  text-decoration: none;
  position: relative;
  margin-right: .35rem;
  padding-right: .5rem
}

.bubble .wave1 {
  background-image: url('../assets/img/img_bubble_wave1.png')
}

.bubble .wave1,.bubble .wave2 {
  display: block;
  width: .8rem;
  height: .8rem;
  background-size: .8rem;
  position: absolute;
  top: .5rem;
  left: .65rem
}

.bubble .wave2 {
  background-image: url('../assets/img/img_bubble_wave2.png')
}

.bubble .wave3 {
  width: .8rem;
  height: .8rem;
  background-image: url('../assets/img/img_bubble_wave3.png');
  background-size: .8rem;
  top: .5rem;
  left: .65rem
}

.bubble .gift,.bubble .wave3 {
  display: block;
  position: absolute
}

.bubble .gift {
  width: 1rem;
  height: 1rem;
  background: url('../assets/img/img_bubble_gift.png') no-repeat;
  background-size: contain;
  top: .5rem;
  left: .75rem
}

.bubble .gift-swing {
  animation: swing 3s infinite linear;
  -webkit-animation: swing 3s infinite linear
}

.bubble .bubble-tail {
  width: .83rem;
  height: 1.185rem;
  position: absolute;
  bottom: 0;
  left: -.3rem;
  background-image: url('../assets/img/img_bubble_tail_yellow.png');
  background-size: .83rem 1.185rem;
}

.bubble .bubble-duration {
  float: right;
  font-size: .65rem
}

.bubble.bubble-red {
  background: #f85f48
}

.bubble.bubble-red .bubble-tail {
  background-image: url('../assets/img/img_bubble_tail_red.png')
}

.bubble.bubble-yellow {
  background: #ffbd17;
}

.bubble.bubble-yellow.bubble-tail {
  background-image: url('../assets/img/img_bubble_tail_yellow.png')
}

.bubble.bubble-yidian {
  background: #a0e75a
}

.bubble.bubble-yidian .bubble-tail {
  background-image: url()
}

.bubble.bubble-playing .bubble-playing {
  visibility: hidden
}

.bubble-duration {
  float: left;
  line-height: 2.2rem;
  color: #c3c3c3;
  font-size: .8rem;
}

</style>
